package com.analyze.datasource.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.analyze.datasource.mgr.DataSourceMgr;
import com.analyze.datasource.po.DataSource;
import com.analyze.datasource.po.DatabaseDriver;

@Controller
public class DataSourceController {
	
	@Autowired
	DataSourceMgr dataSourceMgr;
		
	@RequestMapping("/doAddDataSource.do")
	public String doAddDataSource(HttpServletRequest request){
		DataSource datasource = new DataSource();
		datasource.setName(request.getParameter("name"));
		datasource.setHost(request.getParameter("host"));
		datasource.setPort(request.getParameter("port"));
		datasource.setDbName(request.getParameter("dbName"));
		datasource.setUserName(request.getParameter("userName"));
		datasource.setPassword(request.getParameter("password"));
		String driverID =  request.getParameter("driverID");
		DatabaseDriver driver = dataSourceMgr.getDataBaseDriver(Long.parseLong(driverID));
		datasource.setDriver(driver);
		dataSourceMgr.saveDataSource(datasource);
		
		return  "redirect:/listDataSource.do";
	}
	
	@RequestMapping("/listDataSource.do")
	public ModelAndView listDataSource(HttpServletRequest request){
		List<DataSource> dataSources = dataSourceMgr.getAllDataSource();
		return new ModelAndView("/analyze/listDataSource","dataSources",dataSources);
	}
	
	@RequestMapping("/addDataSource.do")
	public ModelAndView addDataSourcePage(HttpServletRequest request){
		List<DatabaseDriver> databaseDrivers = dataSourceMgr.getAllDBDriver();
		return new ModelAndView("/analyze/addDataSource","databaseDrivers",databaseDrivers);
	}
	
	@RequestMapping("/editDataSource.do")
	public ModelAndView editDataSource(HttpServletRequest request){
		String id = request.getParameter("id");
		DataSource dataSource = dataSourceMgr.getDataSource(Long.parseLong(id));
		return new ModelAndView("/analyze/editDataSource","dataSource",dataSource);
	}
	
	@RequestMapping("/deleteDataSource.do")
	public String deleteDataSource(HttpServletRequest request){
		String id = request.getParameter("id");
		dataSourceMgr.deleteDataSource(Long.parseLong(id));
		return  "redirect:/listDataSource.do";
	}
}
